package com.printeverywhere.delegator;

import static com.printeverywhere.util.AttributeConstants.CLOSING_SESSION;
import static com.printeverywhere.util.LoggerConstants.USERLISTSEARCHCRITERIA;
import static com.printeverywhere.util.LoggerConstants.USERLISTSEARCHCRITERIAEXCEPTION;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.printeverywhere.dto.BlockedBuyer;
import com.printeverywhere.dto.User;
import com.printeverywhere.util.AttributeConstants;
import com.printeverywhere.util.HibernateUtil;

public class BlockBuyerDelegator {
	private static Logger log = Logger.getLogger(BlockBuyerDelegator.class);
		
	public static List<BlockedBuyer> getBlockedBuyer() throws HibernateException {
		
		if(log.isInfoEnabled()){
			log.info("Blocked Buyer list".intern());
		}
		Session session = HibernateUtil.getSession();		
		Transaction tx=null;
		List<BlockedBuyer> BlockBuyer;
		try{
			BlockBuyer = session.createCriteria(BlockedBuyer.class).list();
			return BlockBuyer;
		}
		catch(RuntimeException e) {
			log.error("Got exception when insert user with search criteria".intern());
			if (tx != null)
				tx.rollback();
			throw e;
		} finally {
			if(log.isInfoEnabled()){
				log.info(CLOSING_SESSION);
			}
			session.flush();
			session.close();
		}
	}
	
	public static void insertUser(BlockedBuyer block) throws HibernateException {
		if(log.isInfoEnabled()){
			log.info("Called insertUser method".intern());
		}
		Session session = HibernateUtil.getSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			session.save(block);
			tx.commit();
		} catch (RuntimeException e) {
			log.error("Got exception when insert user with search criteria".intern());
			if (tx != null)
				tx.rollback();
			throw e;
		} finally {
			if(log.isInfoEnabled()){
				log.info(CLOSING_SESSION);
			}
			session.flush();
			session.close();
		}
	}
	
	public static User getUserByUserId(String userId)throws HibernateException {
		if(log.isInfoEnabled()){
			log.info(USERLISTSEARCHCRITERIA);
		}

		Session session = HibernateUtil.getSession();
		Criteria criteria = session.createCriteria(User.class);
		criteria.add(Restrictions.eq(AttributeConstants.USER_ID, userId));
		Transaction transaction = session.beginTransaction();
		List<User> userList;
		try {
			userList = criteria.list();
			transaction.commit();
		} catch (HibernateException e) {
			log.error(USERLISTSEARCHCRITERIAEXCEPTION);
			throw e;
		} finally {
			if(log.isInfoEnabled()){
				log.info(CLOSING_SESSION);
			}
			session.flush();
			HibernateUtil.closeSession();
		}
		return (userList.size() == 0) ? new User() : userList.get(0);
	}
	
	
		
}
